//百度地图包 http://lbsyun.baidu.com/index.php?title=wxjsapi/wxjs-download
const bmap = require('./../libs/map/bmap-wx.js');

//检验授权项及提示前往授权
const getSetting= function(scope){
  return new Promise((resolve, reject) => {
    if (!scope) return reject("scope授权项为空（string）.");
    wx.getSetting({ //授权校验
      success(res) {
        switch (res.authSetting[scope]){
          case false: //已拒绝过授权
            wx.showModal({
              title: '提示',
              content: '是否前往设置允许获取位置信息',
              success({ confirm }) {
                confirm && wx.openSetting();
              }
            })
            break;
          case undefined: //第一次授权
            wx.authorize({
              scope: scope,
              success() {
                resolve()
              },
              fail() {
                console.log("用户拒绝了授权");
              }
            })
            break;
          case true: //已授权
            resolve()
            break;
        }
      }
    });
  })
}

//百度地图定位 - 逆解析不传入经纬度自动定位逆解析的特性
const regeocoding= function(data){
  return new Promise((resolve, reject) => {
    getSetting("scope.userLocation").then(()=>{
      var BMap = new bmap.BMapWX({
        ak: 'IkSvwkWPwCuICyAjnS0QGBzw'
      });
      BMap.regeocoding({
        location: data ? (data.latitude + ',' + data.longitude) : "",
        success: function (res) {
          console.log("逆解析成功：", res);
          resolve(res);
        },
        fail: function (errdata) {
          console.warn(errdata);
        },
      });
    })
  })
};

//腾讯地图定位
const getLocation= function(){
  return new Promise((resolve, reject)=>{
    getSetting("scope.userLocation").then(()=>{
      wx.getLocation({
        type: 'wgs84',
        altitude: "true",
        success(res) {
          console.log("定位成功：", res);
          regeocoding(res).then(resolve);
        },
        fail() {
          console.warn("定位失败！");
        }
      });
    })
  })
};


export default {
  getLocation,
  regeocoding
}